package com.well.register.event;

import com.alibaba.fastjson.JSONObject;
import com.well.register.console.service.ServerService;
import com.well.register.console.service.UserService;
import com.well.register.data.DataCenter;
import com.well.rpc.model.EventType;
import com.well.rpc.model.RegisterModel;
import com.well.rpc.model.TransData;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 服务注册事件
 */
@Component
public class RegisterEvent implements AppEvent {
    private static Logger logger = LoggerFactory.getLogger(RegisterEvent.class);

    @Resource
    public UserService userService;
    @Resource
    private ServerService serverService;

    @Override
    public void doEvent(ChannelHandlerContext channelHandlerContext, TransData transData) {

        RegisterModel model = getRegisterModel(channelHandlerContext, transData);
        if (model == null) {
            ServerHandler.exception(channelHandlerContext,"Register Fail！");
            channelHandlerContext.close();
            return;
        }
        //channel校验。
        int count = userService.getUser(model.getAccessKey());
        if (count < 1) {
            ServerHandler.exception(channelHandlerContext,"AccessKey Error！");
            channelHandlerContext.close();
            return;
        }
        if (DataCenter.registerChannel(model, channelHandlerContext)) {
            //服务注册成功，获取GROUP注册信息
            DataCenter.registerServerModel(model);
            List<RegisterModel> serverModels = DataCenter.getGroupListRegisterModel(model.getNameSpace(), model.getGroup());
            DataCenter.notifyAllNode(model, serverModels);
            //记录服务上线事件
            serverService.serverUp(model);
            logger.info("Register Server Success：" + model.getServerName());
        } else {
            channelHandlerContext.close();
        }
    }

    @Override
    public EventType eventType() {
        return EventType.REGISTER;
    }

    /**
     * 获取注册模型
     * @param channelHandlerContext context
     * @param transData data
     * @return registerModel
     */
    private static RegisterModel getRegisterModel(ChannelHandlerContext channelHandlerContext, TransData transData) {
        RegisterModel registerModel = null;
        try {
            String remoteAddress = ServerHandler.getRemoteAddress(channelHandlerContext);
            String ip = remoteAddress.split(":")[0].replace("/", "");
            registerModel = JSONObject.parseObject(transData.getJsonData(), RegisterModel.class);
            registerModel.setServerIp(ip);
            registerModel.setSubThreadAddr(remoteAddress);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return registerModel;
    }

    /**
     * 记录服务下线事件
     * @param ctx
     */
    public void serverDown(ChannelHandlerContext ctx) {
        String remoteAddress = ServerHandler.getRemoteAddress(ctx);
        RegisterModel model = DataCenter.getRegisterModel(remoteAddress);
        if (model == null) {
            return;
        }
        serverService.serverDown(model);
        logger.info("One server is disconnected, Notice others move it.");
        DataCenter.removeServer(ctx);
    }
}
